package com.example.oop.Service;

import com.example.oop.ChatRoom.ChatRoomManager;
import com.example.oop.POJO.ChatRoom;
import com.example.oop.POJO.Player;
import com.example.oop.Repository.PlayerRepository;
import com.example.oop.Repository.RepositoryManager;
import org.json.JSONException;
import org.json.JSONObject;

//操作：创建当前用户的player，设置状态为1（准备）
public class ReadyService {
    private final PlayerRepository playerRepository;

    public ReadyService() {
        playerRepository = RepositoryManager.playerRepository;
    }

    public synchronized JSONObject ready(JSONObject args) throws JSONException {
        synchronized (RepositoryManager.playerRepository) {
            JSONObject response = new JSONObject();  //定义用来响应的JSON

            //用户点击准备按钮，玩家不存在则创建玩家
            //用户ID为自增,用户名为前端传入，status为1表示准备状态
            Player player;
            if (!playerRepository.findByUsername(args.optString("username")).isPresent()) { //当前用户不存在
                player = new Player(0, args.optString("username"), 1);  //创建当前用户
            } else { //当前用户已存在
                player = playerRepository.findByUsername(args.optString("username")).get();
                player.setStatus(1);
            }
            playerRepository.save(player);

            //创建聊天者
            ChatRoom chatRoom = ChatRoomManager.i.createChatRoom(args.optString("username"));

            JSONObject data = new JSONObject();
            data.put("username", args.optString("username"));
            data.put("chatRoomId", chatRoom.getId());

            response.put("status", 0);
            response.put("data", data);
            response.put("reason", "正在为您匹配对手！");

            return response;
        }
    }
}
